package com.work.yshop.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.work.yshop.R;
import com.work.yshop.adapter.SearchResultListAdapter;
import com.work.yshop.databinding.ActivitySearchResultsBinding;
import com.work.yshop.model.Product;
import com.work.yshop.mvp.contract.SearchResultsContract;
import com.work.yshop.mvp.presenter.SearchResultsPresenter;

import java.util.List;

public class SearchResultsActivity extends AppCompatActivity implements 
        SearchResultsContract.View, View.OnClickListener {

    private ActivitySearchResultsBinding binding;
    private SearchResultListAdapter adapter;
    private SearchResultsContract.Presenter presenter;

    /**
     * 启动搜索结果页面的静态方法
     * @param context 上下文
     * @param query 搜索关键词（可选）
     */
    public static void start(Context context, String query) {
        Intent intent = new Intent(context, SearchResultsActivity.class);
        if (query != null && !query.isEmpty()) {
            intent.putExtra("query", query);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 设置状态栏
        setupStatusBar();
        
        binding = ActivitySearchResultsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        // 初始化Presenter
        presenter = new SearchResultsPresenter(this);
        ((SearchResultsPresenter) presenter).attachView(this);
        
        // 初始化视图
        initViews();
        
        // 设置事件监听
        setupListeners();
        
        // 获取传递过来的搜索关键词（如果有）
        String query = getIntent().getStringExtra("query");
        if (query != null) {
            binding.etSearch.setText(query);
            performSearch(query);
        }
    }
    
    /**
     * 设置状态栏
     */
    private void setupStatusBar() {
        // 让内容区域延伸到状态栏
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        
        // 设置状态栏图标为深色
        WindowInsetsControllerCompat controller = new WindowInsetsControllerCompat(getWindow(), getWindow().getDecorView());
        controller.setAppearanceLightStatusBars(true); // 状态栏文字和图标为黑色
        
        // 设置状态栏颜色为透明
        getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
    }

    private void initViews() {
        // 设置RecyclerView为线性布局
        binding.recyclerSearchResults.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SearchResultListAdapter(this);
        binding.recyclerSearchResults.setAdapter(adapter);
        
        // 设置搜索栏上边距，避免被状态栏遮挡
        int statusBarHeight = getStatusBarHeight();
        binding.searchHeader.setPadding(
            binding.searchHeader.getPaddingLeft(),
            statusBarHeight,
            binding.searchHeader.getPaddingRight(),
            binding.searchHeader.getPaddingBottom()
        );
    }
    
    /**
     * 获取状态栏高度
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private void setupListeners() {
        // 返回按钮点击事件
        binding.btnBack.setOnClickListener(this);
        
        // 搜索按钮点击事件
        binding.btnSearch.setOnClickListener(this);
        
        // 筛选按钮点击事件
        binding.btnFilter.setOnClickListener(this);
        
        // 排序选项点击事件
        binding.tvSortComprehensive.setOnClickListener(this);
        binding.tvSortSales.setOnClickListener(this);
        binding.tvSortPrice.setOnClickListener(this);
        binding.tvFilter.setOnClickListener(this);
        
        // 搜索框编辑完成事件（点击键盘上的搜索键）
        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH 
                    || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                String query = binding.etSearch.getText().toString().trim();
                performSearch(query);
                return true;
            }
            return false;
        });
        
        // 商品点击事件
        adapter.setOnItemClickListener(position -> {
            Product product = adapter.getProductAtPosition(position);
            if (product != null) {
                // 跳转到商品详情页面
                ProductDetailActivity.start(this, product.getId());
            }
        });
        
        // 购买按钮点击事件
        adapter.setOnBuyClickListener(position -> {
            Product product = adapter.getProductAtPosition(position);
            if (product != null) {
                // 跳转到商品详情页面并显示购买选项
                ProductDetailActivity.start(this, product.getId());
                Toast.makeText(this, "准备购买: " + product.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    @Override
    public void onClick(View v) {
        if (v == binding.btnBack) {
            finish();
        } else if (v == binding.btnSearch) {
            // 无需判断是否为空，直接执行搜索
            performSearch(binding.etSearch.getText().toString().trim());
        } else if (v == binding.btnFilter || v == binding.tvFilter) {
            Toast.makeText(this, "筛选功能", Toast.LENGTH_SHORT).show();
        } else if (v == binding.tvSortComprehensive) {
            updateSortUI(binding.tvSortComprehensive);
            presenter.sortByComprehensive();
        } else if (v == binding.tvSortSales) {
            updateSortUI(binding.tvSortSales);
            presenter.sortBySales();
        } else if (v == binding.tvSortPrice) {
            updateSortUI(binding.tvSortPrice);
            presenter.sortByPrice();
        }
    }
    
    /**
     * 更新排序UI
     */
    private void updateSortUI(View selectedTab) {
        // 重置所有标签样式
        binding.tvSortComprehensive.setTextColor(0xFF666666);
        binding.tvSortSales.setTextColor(0xFF666666);
        binding.tvSortPrice.setTextColor(0xFF666666);
        
        // 设置选中的标签样式
        if (selectedTab instanceof TextView) {
            ((TextView) selectedTab).setTextColor(0xFF333333);
        }
    }
    
    /**
     * 执行搜索
     */
    private void performSearch(String query) {
        // 允许空字符串搜索，将显示所有商品
        presenter.searchProducts(query);
        
        // 收起键盘
        hideKeyboard(binding.etSearch);
    }
    
    /**
     * 隐藏软键盘
     */
    private void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
    
    @Override
    public void showLoading() {
        binding.progressBar.setVisibility(View.VISIBLE);
        binding.recyclerSearchResults.setVisibility(View.GONE);
        binding.emptyView.setVisibility(View.GONE);
    }

    @Override
    public void hideLoading() {
        binding.progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showSearchResults(List<Product> products) {
        binding.recyclerSearchResults.setVisibility(View.VISIBLE);
        binding.emptyView.setVisibility(View.GONE);
        adapter.setData(products);
    }

    @Override
    public void showEmptyResults() {
        binding.recyclerSearchResults.setVisibility(View.GONE);
        binding.emptyView.setVisibility(View.VISIBLE);
    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
        binding = null;
    }
} 